<template>
	<div class="order">
		<!-- 收获地址 -->
		<div class="address" @click="selectAddress">
			<div class="address_wrapper" v-if="address">
				<div class="address_top">
					<img src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/recruit/icon/people.png"  class="address_top_header">
					<div class="address_top_nick">{{address.consignee}}</div>
					<img src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/recruit/icon/tel.png"  class="address_top_phone">
					<div class="address_top_tel">{{address.phone}}</div>
				</div>
				<div class="address_bottom">
					{{address.province}}-{{address.city}}-{{address.area}}-{{address.add_detail}}
				</div>
			</div>
			<div v-else class="address_tip">填写收获地址</div>
			<img src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/recruit/icon/right.png"  class="right_arrow">
		</div>
		<!-- 收获地址结束 -->

		<!-- 订单列表 -->
		<div class="orderList">
			<div>商品列表</div>
			<div class="orderList_item" v-for="(value,index) in goodsDetail.goods_info" :key="index" @click="toGoodsDetail(value.good_id)">
				<img :src="value.thumb_url">
				<div class="orderList_item_content">
					<div class="orderList_item_content_top">
						<div class="orderList_item_content_top1">
							<!-- <span>海外购</span> -->
							<span>
                  {{value.name}}
                </span>
						</div>
						<div class="orderList_item_content_top2" v-if="shopType=='common'">￥{{value.goods_spu_info.price}}</div>
						<div class="orderList_item_content_top2" v-if="shopType=='integral'">积分: {{value.exchange_integral}}</div>
					</div>
					<div class="orderList_item_content_bottom">
						<div class="orderList_item_content_bottom1" v-if="shopType=='common'||shopType=='bargin' ||shopType=='group'">
							<!--              {{value.goods_spu_info.spu_name}}-->
							{{value.goods_spu_info.size_spu_name==''?'':(value.goods_spu_info.size_spu_name+'码')}}
							{{value.goods_spu_info.color_spu_name==''?'':('，'+value.goods_spu_info.color_spu_name)}}
						</div>
						<div class="orderList_item_content_bottom2">x {{value.goods_num}}</div>

					</div>
					<div class="orderList_item_content_bottom">
						<div class="orderList_item_content_bottom2" style="color: red">
							<span v-for="(item,ids) in value.discount_name" :key="item">【{{item}}】</span>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 订单列表结束 -->

		<!-- 订单信息 -->
		<div class="order_information">
			<div class="order_information_item">
				<div>支付方式</div>
				<!--        <div v-if="shopType=='integral'">积分支付</div>-->
				<!--        <div>在线支付</div>-->
				<picker @change="selectPayType" :value="payType" :range="payArray" style="margin-right:10px;">
					<view class="picker">
						{{payArray[payType]}}
						<span style="color: red" v-if="payArray[payType]!='微信支付'&&goodsDetail.goods_total_amount_balance>discount_info.available_money">
                余额不足
            </span>
					</view>
				</picker>
			</div>
			<!--       <div class="order_information_item">
                    <div>配送快递</div>
                    <picker @change="selectPayType" :value="payType" :range="payArray" style="margin-right:10px;">
                      <view class="picker">
                        {{payArray[payType]}}
                      </view>
                    </picker>
                  </div> -->
			<!--       <div class="order_information_item">
                    <div>发票信息</div>
                    <picker @change="selectPayType" :value="payType" :range="payArray" style="margin-right:10px;">
                      <view class="picker">
                        {{payArray[payType]}}
                      </view>
                    </picker>
                  </div> -->
			<!--       <div class="order_information_item">
                    <div>储值卡</div>
                    <picker @change="selectPayType" :value="payType" :range="payArray" style="margin-right:10px;">
                      <view class="picker">
                        {{payArray[payType]}}
                      </view>
                    </picker>
                  </div> -->
			<!--      <div class="order_information_item">-->
			<!--        <div>快递方式</div>-->
			<!--        &lt;!&ndash; <picker @change="selectCompanyIndex" :value="companyIndex" :range="companyArr" style="margin-right:10px;">-->
			<!--          <view class="picker">-->
			<!--            {{companyArr[companyIndex]}}-->
			<!--          </view>-->
			<!--        </picker> &ndash;&gt;-->
			<!--        <div>{{company.name}}</div>-->
			<!--      </div>-->
			<!--      <div class="order_information_item" v-if="shopType=='integral'">-->
			<!--        <div>积分消费</div>-->
			<!--        <div>{{goodsDetail.goods_info[0].exchange_integral*goodsDetail.goods_info[0].goods_num}}</div>-->
			<!--      </div>-->
			<div class="order_information_item">
				<div>折扣</div>
				<div>{{payArray[payType]!='微信支付'?discount_info.discount_info.name:'无'}}</div>
			</div>
			<!--      <div class="order_information_item">-->
			<!--        <div>促销活动</div>-->
			<!--        <div>-->
			<!--          <span v-for="(item,index) in goodsDetail.discount_info.name" :key="item">{{item}}{{index==(goodsDetail.discount_info.name.length-1)?'':'，'}}</span>-->
			<!--        </div>-->
			<!--      </div>-->
			<!--      <div class="order_information_item" @click="toCoupon" v-if="shopType=='common'">-->
			<!--        <div>优惠券</div>-->
			<!--        <div>{{coupon.name||'未使用 >'}}</div>-->
			<!--      </div>-->
			<div class="order_information_item">
				<div>商品金额</div>
				<div>￥{{goodsDetail.goods_amount}}</div>
			</div>
			<div class="order_information_item">
				<div>促销减</div>
				<div>￥{{goodsDetail.discount_info.reduce}}</div>
			</div>
			<div class="order_information_item">
				<div>会员优惠</div>
				<div>{{payArray[payType]!='微信支付'?'￥'+goodsDetail.balance_reduce:'无'}}</div>
			</div>
			<div class="order_information_item">
				<div>运费</div>
				<div v-if="payArray[payType]!='微信支付'">{{goodsDetail.express_fee_balance=='包邮'?goodsDetail.express_fee_balance:"￥"+goodsDetail.express_fee_balance}}</div>
				<div v-if="payArray[payType]=='微信支付'">{{goodsDetail.express_fee=='包邮'?goodsDetail.express_fee:"￥"+goodsDetail.express_fee}}</div>
			</div>
			<div class="order_information_remark">
				<div>备注</div>
				<input type="text" placeholder="如需备注请输入" v-model="remark">
			</div>
		</div>
		<!-- 订单信息结束 -->
		<div class="pay">
			<div v-if="payArray[payType]=='微信支付'">合计：￥{{goodsDetail.express_fee=='包邮'?goodsDetail.goods_total_amount:goodsDetail.goods_total_amount+goodsDetail.express_fee}}</div>
			<div v-if="payArray[payType]!='微信支付'">合计：￥{{goodsDetail.express_fee_balance=='包邮'?goodsDetail.goods_total_amount_balance:(goodsDetail.goods_total_amount_balance*100+goodsDetail.express_fee_balance*100)/100}}</div>
			<div class="pay_btn" @click="orderConfirm">确认并付款</div>
			<!--      <div class="pay_btn" @click="orderConfirm" v-if="shopType=='integral'">立即兑换</div>-->
		</div>

		<div class="module" @click.stop="offPay" v-if="balanceShow">
			<div class="module-pay">
				<img class="del-icon" :src="FileUrl+'del.png'" @click.stop="offPay"/>
				<div class="title">番禺供销社百越网购</div>
				<div class="balance">{{goodsDetail.express_fee_balance=='包邮'?goodsDetail.goods_total_amount_balance:(goodsDetail.goods_total_amount_balance*100+goodsDetail.express_fee_balance*100)/100}}</div>
				<div class="tips">
					<span>付款方式</span>
					<span>账户余额（{{discount_info.discount_info.name}}）</span>
				</div>
				<div class="btn">
					<div class="to-pay" @click.stop="balancePayment">付款</div>
				</div>
			</div>
		</div>

		<!--    -->
	</div>
</template>

<script>


export default {
	name:'order',
	data(){
		return {
			FileUrl: this.$base,
			payType:0,
			payArray:['微信支付', '余额支付'],
			companyId:[],
			companyArr:[],
			companyIndex:0,
			orderId:"",   //订单号
			remark:"",    //备注信息
			address:"",  //地址详情
			company:'',//快递公司
			type:'',//订单类型shop_cart来自购物车
			shopType:'',//integral积分,bargain砍价,common普通商品
			balanceShow: false,
			myBalance: 0,
			order_num: '',
			discount_info: ''
		}
	},
	computed: {
		goodsDetail(){
			return this.$store.state.modulesOrder.order
		},
		coupon:{
			get:function(){
				return this.$store.state.modulesCoupon.coupon
			}
		}
	},
	watch:{
		coupon(nval){
			if(nval){
				this.$set(this.goodsDetail,'goods_total_amount',nval.goods_money)
			}
		},
		goodsDetail(nval){
			// if(nval.goods_info[0].type=='integral'){
			//   this.credit=true;
			// }else{
			//   this.credit=false
			// }
			switch(nval.goods_info[0].type){
				case 'integral': this.shopType='integral';break;
				case 'bargain':this.shopType='bargain';break;
				case 'common':this.shopType='common';break;
				case 'group':this.shopType='group';break;
			}
		},
		shopType(nval){
			console.log(this.$store.state.modulesOrder.order,44444)
		}
	},
	// onHide(){
	//   console.log("hide")
	//   this.$store.dispatch('setCoupon',{...{},...{}});
	// },
	onUnload(){
		console.log("onUnload")
		this.$store.dispatch('setCoupon',{...{},...{}});
	},
	methods:{
		async getExpressFee(){
			let params = {
				province: this.address.province,
				num: this.goodsDetail.goods_total_num||1,
				cart_ids: [],
				goods_id: ''
			}
			if (this.goodsDetail.shop_cart) {
				this.goodsDetail.shop_cart.forEach(item=>{
					params.cart_ids.push(item)
				})
				params.goods_id = ''
			}else {
				params.goods_id = this.goodsDetail.goods_info[0].id;
			}
			let res = await this.$request.postData('/order/getProvinceExpressFee',params)
			if (res.data.level == 'success'){
				if(this.goodsDetail.goods_total_amount_balance >= this.goodsDetail.express_info.order_free_shipping_price||this.goodsDetail.goods_total_num >= this.goodsDetail.express_info.order_free_shipping_num){
					this.goodsDetail.express_fee_balance = "包邮";
				}else {
					this.goodsDetail.express_fee_balance = res.data.data;
				}
				if (this.goodsDetail.goods_total_amount >= this.goodsDetail.express_info.order_free_shipping_price||this.goodsDetail.goods_total_num >= this.goodsDetail.express_info.order_free_shipping_num) {
					this.goodsDetail.express_fee = "包邮";
				}else {
					this.goodsDetail.express_fee = res.data.data;
				}
			}

		},
		offPay(){
			this.balanceShow=false;
			let _this=this;
			// _this.$currency.showToast(res.data.message,1500);
			setTimeout(()=>{
				uni.redirectTo({url:'/pages/orderDetail/orderDetail?num='+this.order_num})
			},1500)
		},
		selectPayType(e){
			this.payType=e.target.value;
		},
		selectAddress(){
			uni.navigateTo({url:'/pages/address/address?orderId='+this.orderId})

		},
		async getExpressCompany(){//获取快递公司列表
			let res=await this.$request.getData('/other/getExpressCompany')
			if(res.data.level=='success'){
				this.company=res.data.data
			}
		},
		async orderConfirm(){//生成订单
			let userToken = wx.getStorageSync('userToken');
			if(this.address=='') {
				uni.showToast({title:'未填写收获地址',icon:"none"})
				let value = this.goodsDetail
				setTimeout(() => {
					uni.navigateTo({url:`/pages/address/address`})
				}, 1000)
				return
			}
			let payType = '';
			if (this.payArray[this.payType] == "微信支付") {
				payType = 'weixin';
			}else {
				payType = 'balance';
			}
			console.log(this.shopType,"shopType")
			if(this.type!='shop_cart'&&this.goodsDetail.goods_info[0].type=='common'){
				console.log(this.goodsDetail.goods_info,"goods_info")
				let res = await this.$request.postData('/order/buildOrder',{
					type:'',
					num:this.goodsDetail.goods_info[0].goods_num,
					goods_id:this.goodsDetail.goods_info[0].id,
					user_token:userToken,
					address_id:this.address.id,
					note:this.remark,
					goods_spu_id:this.goodsDetail.goods_info[0].goods_spu_info.id,
					coupon_id: this.coupon.id||'',
					invite_id: wx.getStorageSync('to_user_id')||'',
					pay_type: payType
				});
				if (res.data.level == 'success'){
					uni.showToast({title:res.data.message,icon:"none"});
					let _this = this;
					setTimeout(()=>{
						if (_this.payArray[_this.payType] == "微信支付"){
							_this.payment(res.data.data.order_num);
						} else{
							_this.balanceShow = true;
							_this.order_num = res.data.data.order_num;
							// this.checkMyBalance(res.data.data.order_num);
						}
					},1500)
				}else if (res.data.level == 'paying'){
					uni.showToast({title:res.data.message,icon:"none"});
					let _this = this;
					setTimeout(()=>{
						uni.redirectTo({url:`/pages/orderDetail/orderDetail?num=${res.data.data.order_num}`})
					},1500)
				}else {
					uni.showToast({title:res.data.message,icon:"none"});
				}
			}else {
				console.log(this.goodsDetail.goods_info,"goodsDetail")
				let res=await this.$request.postData('/order/buildOrder',{//商城直接下单
					type:this.type,
					num:'',
					goods_id:this.goodsDetail.shop_cart,
					user_token:userToken,
					address_id:this.address.id,
					remark:this.remark,
					coupon_id: this.coupon.id||'',
					invite_id: wx.getStorageSync('to_user_id')||'',
					pay_type: payType
				});
				if (res.data.level == 'success'){
					uni.showToast({title:res.data.message,icon:"none"});
					let _this = this;
					setTimeout(()=>{
						if (_this.payArray[_this.payType] == "微信支付"){
							_this.payment(res.data.data.order_num);
						} else{
							_this.balanceShow = true;
							_this.order_num = res.data.data.order_num;
							// this.checkMyBalance(res.data.data.order_num);
						}
					},1500)
				}else if (res.data.level == 'paying'){
					uni.showToast({title:res.data.message,icon:"none"});
					let _this = this;
					setTimeout(()=>{
						uni.redirectTo({url:`/pages/orderDetail/orderDetail?num=${res.data.data.order_num}`})
					},1500)
				}else {
					uni.showToast({title:res.data.message,icon:"none"});
				}
			}


		},
		//获取我的余额
		async checkMyBalance(){
			var userToken=wx.getStorageSync('userToken');
			let res=await this.$request.getData('/payment/checkMyBalance',{
				user_token: userToken
			})
			if (res.data.level == 'success'){
				// this.balanceShow = true;
				// this.order_num = order_num;
				this.discount_info = res.data.data;
				this.payArray = [];
				if (this.goodsDetail.goods_total_amount_balance<res.data.data.available_money) {
					this.payArray = [
						"余额支付"+"("+res.data.data.available_money+")",
						"微信支付"
					]
				}else {
					this.payArray = [
						"微信支付",
						"余额支付"+"("+res.data.data.available_money+")"
					];
				}
			}
		},
		//余额支付
		async balancePayment(){
			this.balanceShow = false;
			var userToken=wx.getStorageSync('userToken');
			let res=await this.$request.postData('/payment/balancePayment',{
				user_token: userToken,
				order_num: this.order_num
			})
			if (res.data.level == 'success'){
				let _this=this;
				uni.showToast({title:res.data.message,icon:"none"});
				setTimeout(()=>{
					uni.redirectTo({url:`/pages/orderDetail/orderDetail?num=${this.order_num}`})
				},2000)
			}else {
				let _this=this;
				uni.showToast({title:res.data.message,icon:"none"});
				setTimeout(()=>{
					uni.redirectTo({url:`/pages/orderDetail/orderDetail?num=${this.order_num}`})
				},2000)
			}
		},
		async payment(order_num){
			let _this=this
			var userToken=wx.getStorageSync('userToken')
			// if(this.address==''){
			//   this.$currency.showToast('未填写收获地址')
			//   setTimeout(()=>{
			//     this.$currency.navigateTo(`/pages/address/main?orderId=${this.orderId}`)
			//   },1000)
			// }
			let res=await this.$request.postData('/payment/weChatPayment',{
				order_num:order_num,
				user_token:userToken,
				remark:this.remark,
				address_id:this.address.id
			})
			let data=res.data.data
			wx.requestPayment({
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success() {
					_this.$currency.showToast('支付成功')
					setTimeout(()=>{
						_this.$currency.redirectTo(`/pages/orderDetail/orderDetail?num=${order_num}`)
					},1500)
				},
				fail(res) {
					console.log('取消支付')
					_this.$currency.showToast('取消支付')
					setTimeout(()=>{
						_this.$currency.redirectTo(`/pages/orderDetail/orderDetail?num=${order_num}`)
					},1500)
				}
			})

		},
		async getAddressDetails(){
			var userToken=wx.getStorageSync('userToken')
			if(this.$store.state.modulesAddress.address){
				this.address=this.$store.state.modulesAddress.address;
				this.getExpressFee();
				return
			}
			let res=await this.$request.getData('/ucenter/getShippingAddress',{user_token:userToken})
			let address=res.data.data.filter((item)=>{
				return item.is_default=='1'
			})
			if(address.length!=0){
				this.address=address[0];
				this.getExpressFee();
			}else{
				this.address=''
			}
		},
		toGoodsDetail(id){
			this.$currency.navigateTo('/pages/goodsDetail/goodsDetail?id='+id)
		},
		toCoupon(){
			var userToken=wx.getStorageSync('userToken')
			if(this.type=='shop_cart'){
				var type='shop';
				var goods_arr=this.goodsDetail.goods_info.map((val)=>{
					return {'good_id':val.id,'num':val.goods_num,'goods_spu_id':val.goods_spu_info.id}
				})
				var req={
					'type':type,
					user_token:userToken,
					goods_id:goods_arr,
				}
			}else{
				var type='';
				var req={
					'type':type,
					user_token:userToken,
					goods_id:this.goodsDetail.goods_info[0].id,
					num:this.goodsDetail.goods_info[0].goods_num,
					goods_spu_id:this.goodsDetail.goods_info[0].goods_spu_info.id,
				}
			}
			const params=JSON.stringify(req)
			this.$currency.navigateTo(`/pages/coupon/coupon?type=order&params=${params}`)
		}
	},
	onLoad(options){
		this.type= '';
		if(options.type=='cart'){
			this.type='shop_cart'
		}
		// if (this.payType == 1){
		//   this.goodsDetail.goods_total_amount = this.goodsDetail.goods_total_amount - (this.goodsDetail.goods_amount*(1-this.discount_info.rate));
		//   this.goodsDetail.goods_total_amount = this.goodsDetail.goods_total_amount.toFixed(2);
		// }
		console.log(options)
		// this.orderId=options.orderId
		// this.getCartList(options.orderId)
		// if(options.valu==''||options.value==undefined){
		//   this.getAddressDetails()
		// }else{
		//   let value=JSON.parse(options.value)
		//   this.address=value
		// }
	},
	onShow(){
		this.getExpressCompany()
		this.getAddressDetails();
		this.checkMyBalance();
	}
}
</script>

<style scoped lang="scss">
	@import "../../common/css/mixin";
	.order{
		width:100%;
		background: #eee;
		height: 100%;
		font-size: 13px;
	}

	/* 收获地址  */
	.address{
		width:100%;
		min-height: 40px;
		display: flex;
		align-items: center;
		font-size: 12px;
		background: #fff;
		/* border-bottom: 1px dashed gray; */

	}
	.address img{
		width:16px;
		height: 16px;
	}
	.address_wrapper{
		flex:1
	}
	.address_tip{
		margin-left: 10px;
		font-size: 14px;
		flex:1;
	}
	.address_top{
		display: flex;
		align-items: center;
		padding:5px;
		margin-left:10px;
	}
	.address_top_nick{
		margin:0 10px;
	}
	.address_bottom{
		margin-left:20px;
		margin-bottom: 10px;
	}
	.right_arrow{
		margin-right:25px;
	}

	/* 商品列表 */
	.orderList{
		width:100%;
		font-size: 14px;
		line-height: 20px;
		margin-top:20px;
	}
	.orderList>div:nth-child(1){
		padding-left:10px;
		background: #fff;
		height: 30px;
		line-height: 30px;
		border-bottom: 1px solid #eee;
	}
	.orderList_item{
		background: #fff;
		display: flex;
		padding:10px;
		border-bottom: 1px solid #eee;
	}
	.orderList_item>img{
		width:80px;
		height: 80px;
	}
	.orderList_item_content{
		flex:1;
		display: flex;
		align-items: space-around;
		flex-wrap: wrap;
		margin-left:10px;
	}
	.orderList_item_content_top,.orderList_item_content_bottom{
		display: flex;
		justify-content: space-between;
		width:100%;
	}
	.orderList_item_content_top1{
		margin-right:30px;
	}
	/* .orderList_item_content_top1>span:nth-child(1){
      border:1px solid purple;
      color:purple;
      border-radius: 5px;
      font-size: 12px;
    } */
	.orderList_item_content_bottom{
		color:gray;
	}

	/* 订单信息 */
	.order_information{
		width:100%;
		margin-top:20px;
		margin-bottom:60px;
	}
	.order_information_item{
		width:100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		height: 40px;
		border-bottom: 1px solid #eee;
	}
	.order_information_remark{
		width:100%;
		display: flex;
		align-items: center;
		background: #fff;
		height: 40px;
	}
	.order_information_remark>input{
		margin-left:50px;
	}
	.order_information_item>div:nth-child(1),.order_information_remark>div:nth-child(1){
		margin-left:10px;
	}
	.order_information_item>div:nth-child(2){
		margin-right:10px;
		max-width: 60%;
		@include ellipsis(1);
	}

	.pay{
		width:100%;
		position: fixed;
		bottom: 0;
		height: 40px;
		line-height: 40px;
		display: flex;
		justify-content: flex-end;
		background: #fff;
		z-index: 99;
		border-top:1px solid #eee;
	}
	.pay>div:nth-child(1){
		color:red;
		margin-right: 10px;
	}
	.pay_btn{
		color:#fff;
		width:120px;
		text-align: center;
		background: red;
	}

	/* 后续补充的样式 */
	.orderList_item_content_bottom1{
		width:220px;
	}
	.orderList_item_content_bottom2{
		margin-left: auto;
	}
	.module{
		position: fixed;
		z-index: 3000;
		top: 0;
		left: 0;
		width: 100vw;
		min-height: 100vh;
		background: rgba(0,0,0,0.5);
		@include flex();
		flex-direction: column;
	}
	.module-pay{
		width: 80vw;
		border-radius: 16rpx;
		background: #ffffff;
		/*padding: 30rpx;*/
		.del-icon{
			width: 60rpx;
			height: 60rpx;
			padding: 10rpx;
		}
		.title{
			width: 100%;
			text-align: center;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;
		}
		.balance{
			width: 100%;
			text-align: center;
			font-size: 40rpx;
			font-weight: bold;
			height: 100rpx;
			line-height: 100rpx;
		}
		.tips{
			@include flex();
			flex-direction: row;
			border-bottom: 1rpx solid #eeeeee;
			border-top: 1rpx solid #eeeeee;
			span{
				height: 80rpx;
				line-height: 80rpx;
				font-size: 32rpx;
				text-align: center;
				@include ellipsis(1)
			}
			span:first-child{
				width: 30%;
			}
			span:last-child{
				width: 70%;
			}
		}
		.btn{
			width: 100%;
			@include flex();
			flex-direction: column;
			padding: 30rpx 0;
			.to-pay{
				width: 30vw;
				background: #58be6a;
				color: #ffffff;
				border-radius: 16rpx;
				padding: 20rpx 0;
				text-align: center;
			}
		}
	}
</style>
